package net.lzzy.practices.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Newland
 */
@Component
public class JwtUtil {
    private static final String TOKEN_SECRET = "aBcD1234!@#$%^&*()_+";
    /**
     * 静态字段不同于实例字段，无法直接使用Value注入
     * 必须在Component注解的类中使用setter，且对setter进行Value注解
     */
    private static long millis;

    @Value("${app.over.minutes}")
    public void setMinutes(int minutes) {
        JwtUtil.millis = (long) minutes * 60 * 1000;
    }

    /**
     * 生成签名
     * @param userId 用户id
     * @return token
     */

    public static String createToken(String userId) {
        try {
            // 设置过期时间
            Date date = new Date(System.currentTimeMillis() + millis);
            // 私钥和加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            // 设置头部信息
            Map<String, Object> header = new HashMap<>(2);
            header.put("Type", "Jwt");
            header.put("alg", "HS256");
            // 返回token字符串
            return JWT.create()
                    .withHeader(header)
                    .withClaim("userId", userId)
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 检验token是否正确
     * @param token 客户端发来的token
     * @return 返回用户的id
     */
    public static String verifyToken(String token){
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return jwt.getClaim("userId").asString();
        } catch (Exception e){
            return null;
        }
    }
}
